package com.aube.plugin.rank;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aube.plugin.rank.model.CharacterGenerator;
import com.aube.plugin.rank.model.RankAppShare;
import com.aube.plugin.rank.model.RankModel;
import com.aube.plugin.rank.view.FixedSizeImageView;
import com.aube.plugin.rank.view.RankGroup;
import com.aube.plugin.rank.view.RankRefreshLayout;
import com.aube.plugin.rank.view.SelfWrapViewPager;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.IPositionListener;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.dynamicload.OnShareChannelSelected;
import com.huyn.baseframework.model.Category;
import com.huyn.baseframework.model.CategorySimple;
import com.huyn.baseframework.share.ShareModule;
import com.huyn.baseframework.share.ShareType;
import com.huyn.baseframework.statesync.IDataObserver;
import com.huyn.baseframework.utils.StringUtils;
import com.ryg.dynamicload.internal.DLIntent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/5/12.
 */
public class WidgetVpRank extends DLLayout {
    private Context context;
    private IPositionManager mManager;

    private LinearLayout mLayoutGroup;
    private View mFlag, mHeadLayout;
    private TextView mMore, mTitle;
    private CategorySimple mCate;
    private ImageView mArrow;

    private AtomicBoolean mAnimated = new AtomicBoolean(false);
    private List<IPositionListener> mAnimItems = new ArrayList<>();

    private ViewPager mViewPager;
    private RankViewAdpater mAdapter;

    private TextView mTotalRank, mWeekRank, mDes;
    private LinearLayout mTitleLayout;
    private RankRefreshLayout mRefresh;

    private int mThemeColor;

    private RankAppShare mShareData;

    private FixedSizeImageView mToShareImg;

    private View mRuleLayout;
    private ImageView mRuleImg;

    private RankShareHelper mShareHelper;

    public WidgetVpRank(Context context) {
        this(context, null);
    }
    public WidgetVpRank(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public WidgetVpRank(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    @Override
    public void initViews() {
        inflate(R.layout.widget_rank, this, true);
        mLayoutGroup = (LinearLayout) findViewById(R.id.rank_widget_group);

        mFlag = findViewById(R.id.header_flag);
        mTitle = (TextView) findViewById(R.id.header_widget_title);
        mMore = (TextView) findViewById(R.id.header_widget_more);
        mHeadLayout = findViewById(R.id.header_widget_layout);

        mTitleLayout = (LinearLayout) findViewById(R.id.header_widget_title_layout);

        mTotalRank = (TextView) findViewById(R.id.header_widget_total);
        mWeekRank = (TextView) findViewById(R.id.header_widget_week);
        mDes = (TextView) findViewById(R.id.header_widget_des);

        mRuleLayout = findViewById(R.id.rank_widget_rule);
        mRuleImg = (ImageView) findViewById(R.id.rank_widget_rule_img);
        mRuleImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_info));

        mArrow = (ImageView) findViewById(R.id.header_widget_arrow);
        mArrow.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.icon_rightarrow));

        mFlag.setAlpha(0f);
        mTitleLayout.setAlpha(0f);
        mMore.setAlpha(0f);
        mArrow.setAlpha(0f);
        mDes.setAlpha(0f);
    }

    @Override
    public void fillData(Object o) {
        if(o == null || !(o instanceof Category))
            return;

        Category category = (Category) o;
        mCate = category.getSimpleCategory();

        mTitle.setText(category.modelName);

        mLayoutGroup.removeAllViews();

        List list = (List) category.dataDetail;
        List<RankModel> ranks = new ArrayList<>();
        final String[] allIds = new String[list.size()];
        int i=0;
        for(Object obj : list) {
            RankModel rankModel = CharacterGenerator.generatorRankModel(obj);

            Object str = mCate.getStrFromExtra("actorIds");
            if(str != null)
                rankModel.actorIds = (String) str;

            if(rankModel.characters != null && rankModel.characters.size() > 0) {
                ranks.add(rankModel);
            }
            allIds[i] = rankModel.week;
            i++;
        }

        RankNumManager.updateOperateConfig(category, ranks);
        RankNumManager.registWidgetObserver(new IDataObserver() {
            @Override
            public void stateUpdate() {
                updateRankDes();
            }
        });

        mViewPager = new SelfWrapViewPager(getContext());
        mLayoutGroup.addView(mViewPager, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        mAdapter = new RankViewAdpater(ranks);
        mViewPager.setAdapter(mAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if(i == 1) {
                    mTotalRank.setTextColor(Color.WHITE);
                    mWeekRank.setTextColor(0x47ffffff);
                } else {
                    mWeekRank.setTextColor(Color.WHITE);
                    mTotalRank.setTextColor(0x47ffffff);
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        updateRankDes();

        mRefresh = (RankRefreshLayout) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), RankRefreshLayout.class.getName());
        mTitleLayout.addView(mRefresh);

        mRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDataByTitles();
                mRefresh.startLoading();
            }
        });
        mTotalRank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mViewPager.getCurrentItem() == 1)
                    return;
                mViewPager.setCurrentItem(1, true);
            }
        });
        mWeekRank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mViewPager.getCurrentItem() == 0)
                    return;
                mViewPager.setCurrentItem(0, true);
            }
        });

        if(StringUtils.isNotBlank(category.modelDesc)) {
            mMore.setText(category.modelDesc);
            mHeadLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mBridge != null) {
                        DLIntent intent = new DLIntent("com.aube.plugin.rank", "com.aube.plugin.rank.WeekRankActivity");
                        intent.putExtra(WeekRankActivity.INTENT_CATEGORY, mCate);
                        intent.putExtra(WeekRankActivity.INTENT_COLOR, mThemeColor);
                        intent.putExtra(WeekRankActivity.INTENT_IDS, allIds);
                        mBridge.openPluginActivity(intent);
                    }
                }
            });
        } else {
            mMore.setVisibility(View.GONE);
            mArrow.setVisibility(View.GONE);
        }

        if(mShareData == null)
            mShareData = RankAppShare.setupShareData(category);

        if(mShareData != null && mShareData.isShareLogoValid() ) {
            mToShareImg = new FixedSizeImageView(getContext());
            DisplayMetrics dm = getResources().getDisplayMetrics();
            int marginDP = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, dm);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.topMargin = marginDP;
            params.rightMargin = marginDP;
            mLayoutGroup.addView(mToShareImg, params);
            mToShareImg.updateSize(mShareData.width, mShareData.height);
            ImageLoader.getInstance(getContext()).fillImage(mToShareImg, mShareData.shareLogoUrl);
            mToShareImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mBridge != null)
                        mBridge.showShareLayout(new OnShareChannelSelected() {
                            @Override
                            public void onSelected(int i) {
                                if(mShareHelper != null)
                                    mShareHelper.toShare(i);
                            }
                        });
                }
            });

            mShareHelper = new RankShareHelper(getContext(), mShareData, new RankShareHelper.IShareBitmapListener() {
                @Override
                public void onResponse(int type, String bitmap) {
                    if(mBridge != null)
                        mBridge.doShare(getShareModule(type, bitmap));
                }
            });
        }

        Object ruleObj = category.getStrFromExtra("ruleUrl");
        if(ruleObj != null) {
            final String ruleStr = (String) ruleObj;
            if(StringUtils.isNotBlank(ruleStr)) {
                mRuleLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(mBridge != null)
                            mBridge.onClickToWap(null, ruleStr, true);
                    }
                });
            }
        }
    }

    private void updateRankDes() {
        int count = RankNumManager.getLeftChance();
        if(count > 0) {
            Object strDes = mCate.getStrFromExtra("extraDescAndroid");
            if (strDes != null) {
                String str = (String) strDes;
                if (StringUtils.isNotBlank(str)) {
                    if (str.contains("***"))
                        str = str.replace("***", count + "");
                    mDes.setText(str);
                }
            }
        } else {
            Object strDes = mCate.getStrFromExtra("noChanceVoteDescAndroid");
            if (strDes != null) {
                String str = (String) strDes;
                mDes.setText(str);
            }
        }
    }

    /**
     * 组装分享
     */
    private ShareModule getShareModule(int type, String bitmap) {
        if(mShareData == null)
            return null;

        final ShareModule shareModule = new ShareModule();
        shareModule.mShareChannel = type;
        shareModule.shareUrl = mShareData.url;
        if(type == ShareType.WEIBO) {
            shareModule.title = mShareData.weiboTitle;
            shareModule.content = mShareData.weiboTitle;
        } else {
            shareModule.title = mShareData.title;
            shareModule.content = mShareData.content;
        }
        //图片大小不能超过32kb
        shareModule.imagePath = bitmap;
        return shareModule;
    }

    @Override
    public void update(Object data) {
        if(data == null || !(data instanceof Category))
            return;

        Category category = (Category) data;
        List list = (List) category.dataDetail;
        List<RankModel> ranks = new ArrayList<>();
        int i=0;
        for(Object obj : list) {
            RankModel rankModel = CharacterGenerator.generatorRankModel(obj);

            Object str = mCate.getStrFromExtra("actorIds");
            if(str != null)
                rankModel.actorIds = (String) str;

            ranks.add(rankModel);
            //刷新数据
            if(mAdapter != null) {
                RankGroup rankGroup = mAdapter.getViewByPosition(i);
                if(rankGroup != null)
                    rankGroup.update(rankModel.characters);
            }
            i++;
        }

        RankNumManager.updateOperateConfig(category, ranks);
    }

    @Override
    public void update() {
        if(mAdapter != null) {
            for(int i=0; i<mAdapter.getCount(); i++)
                mAdapter.getViewByPosition(i).update();
        }
    }

    protected class RankViewAdpater extends PagerAdapter {

        private List<RankModel> mData;
        private HashMap<Integer, RankGroup> mViews;

        public RankViewAdpater(List<RankModel> data) {
            this.mData = data;
            mViews = new HashMap<>();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            RankModel data = mData.get(position);

            RankGroup view = (RankGroup) DynamicLoaderHelper.loadTargetLayout(context, getDLPluginPackage(), RankGroup.class.getName());
            view.setDLBridge(mBridge);

            mViews.put(position, view);
            container.addView(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);

            view.fillData(data, position > 0, true, true);

            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object obj) {
            container.removeView(mViews.get(position));
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == obj;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        public RankGroup getViewByPosition(int pos) {
            if(mViews == null || mViews.size() <= pos)
                return null;
            return mViews.get(pos);
        }

        public RankModel getRankModelByIndex(int index) {
            if(index < 0 || index >= getCount())
                return null;
            return mData.get(index);
        }
    }

    private void showHeader(int animDelay) {
        ObjectAnimator alphaTitle = ObjectAnimator.ofFloat(mTitleLayout, "alpha", 0, 1);
        alphaTitle.setDuration(300);
        if(animDelay > 0)
            alphaTitle.setStartDelay(animDelay);

        ObjectAnimator alphaDes = ObjectAnimator.ofFloat(mDes, "alpha", 0, 1);
        alphaDes.setDuration(300);
        alphaDes.setStartDelay(200 + animDelay);

        ObjectAnimator alphaMore = ObjectAnimator.ofFloat(mMore, "alpha", 0, 1);
        alphaDes.setDuration(300);
        alphaDes.setStartDelay(200 + animDelay);

        ObjectAnimator alphaArrow = ObjectAnimator.ofFloat(mArrow, "alpha", 0, 1);
        alphaArrow.setDuration(300);
        alphaArrow.setStartDelay(200 + animDelay);

        ObjectAnimator translate = ObjectAnimator.ofFloat(mFlag, "translationY", -mFlag.getHeight(), 0);
        translate.setDuration(300);
        translate.setStartDelay(200 + animDelay);
        translate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mFlag.setAlpha(1f);
            }
        });

        AnimatorSet mSet = new AnimatorSet();
        mSet.playTogether(alphaTitle, alphaMore, alphaDes, alphaArrow, translate);
        mSet.start();
    }

    @Override
    public void notifyAnim(int animDelay) {
        if(mManager == null)
            return;
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        showHeader(animDelay);

        if(mShareHelper != null)
            mShareHelper.preloadImg();

        if(mViewPager.getChildCount() > 0) {
            RankGroup rankGroup = ((RankGroup) mViewPager.getChildAt(0));
            int childCount = rankGroup.getChildCount();
            if(childCount > 0) {
                rankGroup.notifyAnim(animDelay);

                int delay = animDelay + 300 + childCount * 200;
                animImgAndtip(delay);
            }
        }

        if(mAnimItems == null)
            return;
        notifyItemAnim(animDelay + 300);
    }

    private void notifyItemAnim(int animDelay) {
        int i=0;
        for (IPositionListener item : mAnimItems) {
            item.notifyAnim(animDelay + i*200);
            i++;
        }
    }

    private void animImgAndtip(int delay) {
        mRuleLayout.setAlpha(0f);
        mToShareImg.setAlpha(0f);
        ValueAnimator shareAnim = ValueAnimator.ofFloat(0, 1);
        shareAnim.setDuration(300);
        shareAnim.setStartDelay(delay);
        shareAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mToShareImg.setAlpha(value);
            }
        });

        ValueAnimator ruleAnim = ValueAnimator.ofFloat(0, 1);
        ruleAnim.setDuration(300);
        ruleAnim.setStartDelay(200 + delay);
        ruleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mRuleLayout.setAlpha(value);
            }
        });

        shareAnim.start();
        ruleAnim.start();
    }

    @Override
    public void registToManager(IPositionManager manager) {
        if(mManager != null || manager == null)
            return;
        manager.add(this);
        this.mManager = manager;
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
        if(mManager == null || manager == null)
            return;
        manager.remove(this);
        this.mManager = null;
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        try {
            locs[1] = locs[1] + getHeight() / 2;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return locs;
    }

    @Override
    public void setTheme(int themeColor) {
        mThemeColor = themeColor;
        mFlag.setBackgroundColor(themeColor);
    }

    public void getDataByTitles() {
        if(mViewPager == null || mAdapter == null)
            return;
        final int index = mViewPager.getCurrentItem();

        RankGroup rankGroup = mAdapter.getViewByPosition(index);
        if (rankGroup != null) {
            rankGroup.refresh(mAdapter.getRankModelByIndex(index), true, new OnRefreshEndListener() {

                @Override
                public void endLoading() {
                    mRefresh.endLoading();
                }
            });
        }
    }

}